package example.zxing.templist;

import android.content.ClipboardManager;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.List;

import example.zxing.R;

/**
 * @Created by taylor on 10/31/18.
 */

public class ScanResultAdapter extends RecyclerView.Adapter<ScanResultAdapter.ViewHolder> {

    private List<ScanBean> list;
    private Context context;
    private SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");

    public ScanResultAdapter(Context c, List<ScanBean> list) {
        this.list = list;
        this.context = c;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_scan, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final ScanBean item = list.get(position);

        holder.tvTime.setText(df.format(item.getTime()));

        holder.tvInfo.setText(item.getInfo());

        holder.mRootItem.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {

                ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(getAlllRecords());
                Toast.makeText(context, "最新5条记录已复制到系统剪贴板！", Toast.LENGTH_SHORT).show();
                return true;
            }
        });

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvTime, tvInfo;
        LinearLayout mRootItem;

        public ViewHolder(View itemView) {
            super(itemView);
            tvTime = (TextView) itemView.findViewById(R.id.tv_time);
            tvInfo = (TextView) itemView.findViewById(R.id.tv_scan_info);
            mRootItem = (LinearLayout) itemView.findViewById(R.id.ll_root_item);
        }
    }

    public String getAlllRecords() {
        StringBuffer sb = new StringBuffer("");
        for (ScanBean b : list) {
            sb.append(b.getInfo());
            sb.append("\n");
        }
        return sb.toString();
    }

}
